import mqtt from 'mqtt'
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      connection: {
        host: "101.46.56.25",
        // host: "47.99.80.195",
        port: 8083,
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
      },
      client: {
        connected: false,
      },
    }
  },
  computed: {
    ...mapGetters(["sysType", "currentMMSI"]),
    topicEvent() {
      let obj = {}
      for (let item of this.topicList) {
        obj[item.topic] = item.fn
      }
      return obj
    },
  },
  methods: {
    getTopicList(mmsi) {
      return {
        // 定位
        gps: () => {
          return {
            topic: `/${mmsi}/GPS/#`,
            fn: "refreshShipInfo",
          }
        },
        // 主机信息
        mainInfo: () => {
          return {
            topic: `/${mmsi}/MainPropulsion/#`,
            fn: "getMainInfo",
          }
        },
        // 发电机信息
        DGInfo: () => {
          return {
            topic: `/${mmsi}/Generator/#`,
            fn: "getGenerator",
          }
        },
        // 侧推信息
        TGInfo: () => {
          return {
            topic: `/${mmsi}/SideThrusterGenerator/#`,
            fn: "getSideGeneratorInfo",
          }
        },
        // 燃油舱信息
        oilInfo: () => {
          return {
            topic: `/${mmsi}/OilTank/#`,
            fn: "getOilInfo",
          }
        },
        // 总的报警
        alarm: () => {
          return {
            topic: `/${mmsi}/Alarm/#`,
            fn: "getAlarmData",
          }
        },
      }
    },
    getTopic(list, mmsi = this.currentMMSI) {
      const topics = this.getTopicList(mmsi);
      return list.map(m => topics[m](mmsi))
    },
    Uint8ArrayToString(fileData) {
      var dataString = "";
      for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
      }
      return dataString
    },
    // 创建连接
    createConnection() {
      const { host, port, ...options } = this.connection
      const connectUrl = `mqtt://${host}:${port}/mqtt`
      try {
        this.client = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('mqtt.connect error', error)
      }
      this.client.on('error', error => {
        console.log('Connection failed', error)
      })
    },
    // 解析通配符
    matchesPattern(pattern, topic) {
      // Implement logic to check if the topic matches the pattern
      const regex = new RegExp('^' + pattern.replace(/\+/g, '[^/]+').replace(/#/g, '.+') + '$');
      return regex.test(topic);
    },
    // 订阅
    mqttSubscribe(topicList) {
      topicList.forEach(({ topic, fn }) => {
        this.client.subscribe(topic, (err) => {
          if (!err) {
            console.log("订阅成功: ", topic);
          }
        });
        this.client.on('message', (receivedTopic, message) => {
          console.log("receivedTopic: ", receivedTopic)
          if (this.matchesPattern(topic, receivedTopic)) {
            const row = JSON.parse(this.Uint8ArrayToString(message))
            this[fn](row, receivedTopic)
          }
        });
      });
    },
    // 取消订阅
    mqttUnsubscribe(topicList) {
      topicList.forEach(({ topic }) => {
        this.client.unsubscribe(topic, (err) => {
          if (!err) {
            console.log("取消订阅: ", topic)
          }
        })
      })
    }
  },
  created() {
    this.createConnection()
  },
  destroyed() {
    this.client.end()
  }
}
